<?php

namespace App\Http\Controllers\UserApi;

use App\Http\Controllers\Controller;
use App\Http\Controllers\EasyWeChat;
use App\Services\Api\PersonalService;
use App\Models\UserModel;
//use Illuminate\Support\Facades\Request;
use App\Http\Requests\UserApi\PersonalRequest;
use App\Models\Qrcode;

class PersonalController extends Controller
{
    public function __construct(PersonalService $personalService)
    {
        $this->middleware('user_check');
        $this->PersonalService = $personalService;
    }

    public function personal_info(PersonalRequest $requests,UserModel $userModel){
        return $this->PersonalService->personal_info($requests->user()->id,$userModel);
    }

    public function others_index(PersonalRequest $requests,UserModel $userModel){
        return $this->PersonalService->others_index($requests->user_id,$userModel,$requests->user()->id);
    }

    public function edit_user_info(PersonalRequest $requests,UserModel $userModel){
        return $this->PersonalService->edit_user_info($requests,$userModel);
    }

    public function qrcode(Qrcode $qrcode){
        return $this->PersonalService->qrcode($qrcode);
    }

    public function get_wx_phone(PersonalRequest $request){
        try{
            $app = EasyWeChat::app();
            $session = $app->auth->session($request['wx_code']);

            // 查找會員是否存在
            $userObj = $request->user();

            if(empty($userObj)){
                $decryptedData = $app->encryptor->decryptData($session['session_key'],$request['wx_iv'],$request['encryptedData']);
                if(!key_exists('wx_iv',$request) && !key_exists('encryptedData',$request)){
                    throw new \Exception('wx_iv和encryptedData必传');
                }
                if(empty($decryptedData['avatarUrl'])){
                    throw new \Exception('解密失败 请检查参数');
                }
                Log::info(json_encode($decryptedData));

            }

        }catch (\Exception $e){
            return $this->fail(406,$e -> getMessage());
        }
    }
}
